<template>
  <div>
    <a-dropdown v-if="currentUser && currentUser.name" placement="bottomRight">
      <div class="ant-pro-account-avatar">
        <a-avatar size="small" :src="getImageUrl()" class="antd-pro-global-header-index-avatar" />
        <div>{{ currentUser.name.length>5?`${currentUser.name.slice(0,5)}...`:currentUser.name }}</div>
        <div class="role-container" v-if="$store.getters.roles.length">
          <span class="role-tag">{{ $store.getters.roles[0].name }}</span>
          <div class="arrow"></div>
        </div>
      </div>
      <template v-slot:overlay>
        <a-menu class="ant-pro-drop-down menu" :selected-keys="[]">
          <a-menu-item v-if="$auth('PERSON.PERSON_SETTING')" key="settings" @click="handleToSettings">
            <a-icon type="user" />
            {{ $t('all.autotext1221') }}
          </a-menu-item>
          <a-menu-item key="privacy" @click="handleToPrivacy">
            <a-icon type="file" />
            {{ $t('all.autotext436') }}
          </a-menu-item>
          <a-menu-item key="password" @click="clickEditPassword">
            <a-icon type="lock" />
            {{ $t('all.autotext979') }}
          </a-menu-item>
          <a-menu-divider />
          <a-menu-item key="logout" @click="handleLogout">
            <a-icon type="logout" />
            {{ $t('all.autotext51') }}
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
    <span v-else>
      <a-spin size="small" :style="{ marginLeft: 8, marginRight: 8 }" />
    </span>
    <a-modal
      :title="$t('all.autotext791')"
      :visible="modalVisible"
      width="600px"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model
        :model="form"
        :rules="formRules"
        ref="formRef"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item :label="$t('all.autotext734')" prop="pwd">
          <a-input-password v-model="form.pwd" :maxLength="30" :placeholder="$t('all.autotext1261')" />
        </a-form-model-item>
        <a-form-model-item :label="$t('all.autotext168')" prop="pwdConfirm">
          <a-input-password v-model="form.pwdConfirm" :maxLength="30" :placeholder="$t('all.autotext1261')" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>



import { updatePassword } from '@/api/system/user'
import { Modal } from 'ant-design-vue'



export default {
  name: 'AvatarDropdown',
  props: {
    currentUser: {
      type: Object,
      default: () => null
    }
  },
  data () {
    const validatorConfirmPwd = (rule, value, callback) => {
      if (this.form.pwd === this.form.pwdConfirm) {
        callback()
      } else {
        callback(new Error(this.$t('all.autotext1099')))
      }
    }
    return {
      modalVisible: false,
      form: {
        pwd: '',
        pwdConfirm: ''
      },
      labelCol: { span: 5 },
      wrapperCol: { span: 15 },
      formRules: {
        pwd: [
          { required: true, message: this.$t('all.autotext575'), trigger: 'change' },
          { pattern: /^\S*(?=\S{8,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*.? ])\S*$/, message: this.$t('all.autotext1261') }
        ],
        pwdConfirm: [
          { required: true, message: this.$t('all.autotext118'), trigger: 'change' },
          { pattern: /^\S*(?=\S{8,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*.? ])\S*$/, message: this.$t('all.autotext1261') },
          { required: true, trigger: 'blur', validator: validatorConfirmPwd }
        ]
      }
    }
  },
  methods: {
    getImageUrl () {
      if (this.currentUser.headimg) {
        return this.$options.filters.dealImageUrl(this.currentUser.headimg)
      } else {
        return 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png'
      }
    },
    handleToCenter () {
      this.$router.push({ path: '/account/center' })
    },
    handleToSettings () {
      this.$router.push({ path: '/settings' })
    },
    handleToPrivacy () {
      window.open(location.origin + '/privacy', '_target')
    },
    // 点击修改密码
    clickEditPassword () {
      this.modalVisible = true
    },
    handleOk () {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.updatePassword()
        }
      })
    },
    updatePassword () {
      updatePassword({ pwd: this.form.pwd })
        .then(res => {
          this.$message.success(this.$t('all.autotext1020'))
          this.handleCancel()
          this.changePassword()
          // 修改密码成功 退出登录
          this.$store.dispatch('Logout').then(() => {
            this.$router.push({ name: 'login' })
          })
        })
        .catch(() => {})
    },
    // 点击取消关闭对话框并重置
    handleCancel () {
      this.modalVisible = false
      setTimeout(() => {
        this.$refs.formRef.resetFields()
      }, 200)
    },
    handleLogout (e) {
      Modal.confirm({
        title: this.$t('layouts.usermenu.dialog.title'),
        content: this.$t('layouts.usermenu.dialog.content'),
        okText: this.$t('all.autotext792'),
        cancelText: this.$t('all.autotext975'),
        onOk: () => {
          this.$emit('logout', 1)
          // return new Promise((resolve, reject) => {
          //   setTimeout(Math.random() > 0.5 ? resolve : reject, 1500)
          // }).catch(() => console.log('Oops errors!'))
          return this.$store.dispatch('Logout', 1).then(() => {
            this.$router.push({ name: 'login' })
          })
        },
        onCancel () {}
      })
    },
    // 修改密码埋点
    changePassword () {}
  }
}
</script>

<style lang="less" scoped>
.ant-pro-drop-down {
  /deep/ .action {
    margin-right: 8px;
  }
  /deep/ .ant-dropdown-menu-item {
    min-width: 160px;
  }
}
.ant-pro-account-avatar {
  display: flex;
  align-items: center;
  gap: 6px;
  padding-top: 6px;
}
.role-container {
  position: relative;
  display: inline-block;
  top: -2px;
  margin-left: 6px;
}
.arrow {
  position: absolute;
  left: -12px;
  top: 43%;
  width: 0;
  height: 0;
  border: 6px solid transparent;
  border-right-color: #F88A16;
}
.role-tag {
  padding: 5px;
  border-radius: 3px;
  background-color: #F88A16;
}
</style>
